package com.mk.juc.pool;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程线程
 */
@Slf4j
public class ThreadQueue<T> {

    public ThreadQueue(int capacity) {
        this.capacity = capacity;
    }

    /**
     * 线程双向队列
     */
    private final Deque<T> queue = new ArrayDeque<>();

    /**
     * 容量
     */
    private final int capacity;

    /**
     * 锁
     */
    private final ReentrantLock lock = new ReentrantLock();

    /**
     * 生产者阻塞条件变量
     */
    Condition producerSet = lock.newCondition();

    /**
     * 消费者阻塞条件变量
     */
    Condition customerSet = lock.newCondition();


    /**
     * 获取任务
     *
     * @param timeout  超时时间，会转化为纳秒
     * @param timeUnit
     * @return
     */
    public T take(long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanosTimeOut = timeUnit.toNanos(timeout);
            while (queue.isEmpty()) {
                // 如果等待时间小于等于0，则退出等待并返回null
                if (nanosTimeOut <= 0) {
                    return null;
                }
                try {
                    // 返回剩余需要等待的时间，重新赋值给nanosTimeOut
                    nanosTimeOut = customerSet.awaitNanos(nanosTimeOut);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 返回获取任务(同时删除队列中的任务) 并唤醒生产者变量中任意一个执行生产线程的任务
            T task = queue.removeFirst();
            log.info("获取任务: {}", task);
            producerSet.signal();
            return task;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 生产任务
     *
     * @param task 任务
     */
    public void put(T task) {
        lock.lock();
        try {
            while (queue.size() == capacity) {
                try {
                    log.info("添加任务等待: {}", task);
                    producerSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.info("添加新的任务任务：{}", task);
            queue.addLast(task);
            customerSet.signal();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(FullStrategy<T> strategy, T task) {
        lock.lock();
        try {
            if (queue.size() == capacity) {
                strategy.strategy(this, task);
            } else {
                log.info("添加新的任务任务：{}", task);
                queue.addLast(task);
                customerSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}
